package com.xjl.user.applicationInit;

import com.alibaba.fastjson.JSON;
import com.xjl.user.entity.po.UserPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class ApplicationInit implements ApplicationListener<ApplicationReadyEvent> {

    Map<String,InitFuntion> initFuntionMap = new HashMap<>();

    {
        initFuntionMap.put("预热fastJson",this::initFastJson);
    }
    /**
     * 服务启动完成,进行预热的任务
     * @param applicationReadyEvent
     */
    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        initFuntionMap.forEach((desc,function)->{
            try{
                long start = System.currentTimeMillis();
                function.invoke();
                log.info("ApplicationInit{}.costTime {}",desc,System.currentTimeMillis()-start);
            }catch (Exception e){
                log.error("ApplicationInit {},Error!!",desc,e);
            }
        });
    }


    private void initFastJson(){
        UserPO userPO = new UserPO();
        userPO.setId(123123123L);
        userPO.setUserName("test");
        userPO.setSex(1);

        String json = JSON.toJSONString(userPO);
        JSON.parseObject(json,UserPO.class);
    }

    interface InitFuntion{
        void invoke();
    }
}
